<template>
	<div class="sys-config-container">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<TableSearch :search="tb.tableData.search" @search="onSearch" />
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<Table ref="tableRef" v-bind="tb.tableData" :getData="getData" :exportChangeData="exportChangeData" @sortHeader="onSortHeader" @selectionChange="tableSelection" border>
				<template #command>
					<el-button type="primary" icon="ele-Plus" @click="openAddConfig" v-auth="'sysConfig:addData'"> {{ t('system.btn.add') }} </el-button>

					<el-button v-if="state.selectlist.length > 0" type="danger" icon="ele-Delete" @click="bacthDelete" v-auth="'sysConfig:batchDelete'"> {{ t('system.common.batchDelete') }} </el-button>
				</template>
				<template #sysFlag="scope">
					<g-sys-dict v-model="scope.row.sysFlag" code="YesNoEnum" />
				</template>

				<template #isDisable="scope">
					<g-sys-dict v-model="scope.row.isDisable" code="StatusEnum" />
				</template>
				
				<template #remark="scope">
					<ModifyRecord :data="scope.row" />
				</template>
				<template #action="scope">
					<el-button icon="ele-Edit" size="small" text type="primary" @click="openEditConfig(scope.row)" v-auth="'sysConfig:updateData'"> {{ t('system.btn.edit') }} </el-button>
					<el-button icon="ele-Delete" size="small" text type="danger" @click="delConfig(scope.row)" v-auth="'sysConfig:deleteData'" :disabled="scope.row.sysFlag === 1"> {{ t('system.btn.delete') }} </el-button>
				</template>
			</Table>
		</el-card>
		<EditConfig ref="editConfigRef" :title="state.editConfigTitle" :groupList="state.groupList" @updateData="updateData" />
	</div>
</template>

<script lang="ts" setup name="sysConfig">
import { onMounted, reactive, ref, defineAsyncComponent, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { auth } from '/@/utils/authFunction';
import { useI18n } from 'vue-i18n';

import { apiSysConfigGroupListGet,apiSysConfigPagePost,apiSysConfigDeletePost,apiSysConfigBatchDeletePost } from '/@/api-services/api';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import EditConfig from '/@/views/system/config/component/editConfig.vue';
import { EmptyObjectType, RefType } from '/@/types/global';

const { t } = useI18n();

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const editConfigRef = ref<InstanceType<typeof EditConfig>>();
const tableRef = ref<RefType>();

const state = reactive({
	editConfigTitle: '',
	selectlist: [] as EmptyObjectType[],
	groupList: [] as Array<String>,
});

const tb = reactive<TableDemoState>({
	tableData: {
		// 表头内容（必传，注意格式）
		columns: [
			{ prop: 'name', minWidth: 150, label: t('system.config.name'), headerAlign: 'center',   isCheck: true, hideCheck: true },
			{ prop: 'code', minWidth: 150, label: t('system.config.code'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
			{ prop: 'value', minWidth: 150, label: t('system.config.value'), headerAlign: 'center', isCheck: true },
			{ prop: 'sysFlag', width: 100, label: t('system.config.sysFlag'), align: 'center', isCheck: true },
			{ prop: 'groupCode', width: 120, label: t('system.config.groupCode'), align: 'center',  isCheck: true },
			{ prop: 'isDisable', width: 100, label: t('system.common.status'), align: 'center', sortable: 'custom',isCheck: true },
			{ prop: 'sort', width: 80, label: t('system.common.sort'), align: 'center',   isCheck: true },
			{ prop: 'remark', width: 100, label: t('system.common.modifyRecord'), align: 'center', headerAlign: 'center', showOverflowTooltip: true, isCheck: true },
			{ prop: 'action', width: 140, label: t('system.common.operation'), type: 'action', align: 'center', isCheck: true, fixed: 'right', hideCheck: true },
		],
		// 配置项（必传）
		config: {
			isStripe: true, // 是否显示表格斑马纹
			isBorder: false, // 是否显示表格边框
			isSerialNo: true, // 是否显示表格序号
			isSelection: true, // 是否勾选表格多选
			showSelection: auth('sysConfig:batchDelete'), //是否显示表格多选
			pageSize: 50, // 每页条数
			hideExport: false, //是否隐藏导出按钮
			exportFileName: t('system.config.exportFileName'), //导出报表的文件名，不填写取应用名称
		},
		// 搜索表单，动态生成（传空数组时，将不显示搜索，type有3种类型：input,date,select）
		search: [
			{ label: t('system.config.name'), prop: 'name', placeholder: t('system.config.searchName'), required: false, type: 'input' },
			{ label: t('system.config.code'), prop: 'code', placeholder: t('system.config.searchCode'), required: false, type: 'input' },
			// { label: '创建时间', prop: 'time', placeholder: '请选择', required: false, type: 'date' },
		],
		param: {},
		defaultSort: {
			prop: 'sort',
			order: 'ascending',
		},
	},
});
const getData = (param: any) => {
	return apiSysConfigPagePost(param)
		.then((res) => {
			return res.data.data;
		});
};
const exportChangeData = (data: Array<EmptyObjectType>) => {
	data.forEach((item) => {
		item.sysFlag = item.sysFlag == 1 ? '是' : '否';
	});
	return data;
};
// 拖动显示列排序回调
const onSortHeader = (data: object[]) => {
	tb.tableData.columns = data;
};
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
	tb.tableData.param = Object.assign({}, tb.tableData.param, { ...data });
	nextTick(() => {
		tableRef.value.pageReset();
	});
};

const getGroupList = async () => {
	const res = await apiSysConfigGroupListGet();
	const groupSearch = {
		label: t('system.config.groupCode'),
		prop: 'groupCode',
		placeholder: t('system.common.select'),
		required: false,
		type: 'select',
		options: [],
	} as TableSearchType;
	state.groupList = res.data.data ?? [];
	res.data.data?.forEach((item) => {
		groupSearch.options?.push({ label: item, value: item });
	});
	let group = tb.tableData.search.filter((item) => {
		return item.prop == 'groupCode';
	});
	if (group.length == 0) {
		tb.tableData.search.push(groupSearch);
	} else {
		group[0] = groupSearch;
	}
};

//表格多选事件
const tableSelection = (data: EmptyObjectType[]) => {
	state.selectlist = data;
};

onMounted(async () => {
	getGroupList();
});

// 更新数据
const updateData = () => {
	tableRef.value.handleList();
	getGroupList();
};

// 打开新增页面
const openAddConfig = () => {
	state.editConfigTitle = t('system.config.addConfig');
	editConfigRef.value?.openDialog({ sysFlag: 0, sort: 100 });
};

// 打开编辑页面
const openEditConfig = (row: any) => {
	state.editConfigTitle = t('system.config.editConfig');
	editConfigRef.value?.openDialog(row);
};

// 删除
const delConfig = (row: any) => {
	ElMessageBox.confirm(t('system.config.deleteConfirm', { name: row.name }), t('system.common.confirm'), {
		confirmButtonText: t('system.common.confirm'),
		cancelButtonText: t('system.common.cancel'),
		type: 'warning',
	})
		.then(async () => {
			await apiSysConfigDeletePost({ id: row.id });
			tableRef.value.handleList();
			ElMessage.success(t('system.config.deleteSuccess'));
		})
		.catch(() => {});
};

//批量删除
const bacthDelete = () => {
	if (state.selectlist.length == 0) return false;
	ElMessageBox.confirm(t('system.config.batchDeleteConfirm', { count: state.selectlist.length, name: state.selectlist[0].name }), t('system.common.confirm'), {
		confirmButtonText: t('system.common.confirm'),
		cancelButtonText: t('system.common.cancel'),
		type: 'warning',
	})
		.then(async () => {
			const ids = state.selectlist.map((item) => {
				return item.id;
			});
			var res = await apiSysConfigBatchDeletePost(ids);
			tableRef.value.pageReset();
			ElMessage.success(t('system.config.deleteSuccess'));
		})
		.catch(() => {});
};
</script>
